<template>
  <div>
    <el-card class="box-card margin_30">
      <div slot="header" class="clearfix">
        <el-button type="primary" size="mini" @click="goAddRoles(1)">新增角色</el-button>
      </div>
      <el-table
        v-loading="loading"
        :data="list"
        border
        element-loading-text="拼命加载中"
        element-loading-spinner="el-icon-loading"
        element-loading-background="rgba(0, 0, 0, 0.8)"
      >
        <el-table-column
          label="#"
          align="center"
          width="50"
          type="index"
        />
        <!-- prop需要展示的数据部分 -->
        <!-- label表头的名称 -->
        <el-table-column
          prop="roleName"
          label="角色名称"
          align="center"
          width="200"
        />
        <el-table-column
          prop="roleCode"
          label="角色编码"
          align="center"
          width="200"
        />
        <el-table-column
          prop="remark"
          label="备注"
          align="center"
          width="200"
        />
        <el-table-column
          prop="createTime"
          label="添加时间"
          align="center"
          width="250"
        />
        <el-table-column label="操作" align="center" width="200">
          <template slot-scope="scope">
            <el-button size="mini" type="success" @click="goEdit(scope.row.id,0)">编辑</el-button>
            <el-button size="mini" @click="del(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        :current-page="paginationParams.start"
        :page-sizes="paginationParams.pageSize"
        :page-size="paginationParams.limit"
        layout="->, total, sizes, prev, pager, next, jumper"
        :total="paginationParams.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>
    <!-- 弹框出现 -->
    <el-dialog title="编辑角色" :visible.sync="isShowDialog" width="40%" size="mini" @close="handleDialog">
      <el-form :model="formData" label-width="100px" size="mini">
        <el-form-item label="角色名称">
          <el-input v-model="formData.roleName" placeholder="角色名称" autocomplete="off" />
        </el-form-item>
        <el-form-item label="角色编码">
          <el-input v-model="formData.roleCode" placeholder="角色编码" autocomplete="off" />
        </el-form-item>
        <el-form-item label="角色描述">
          <el-input v-model="formData.remark" placeholder="角色描述" autocomplete="off" />
        </el-form-item>
        <el-form-item label="选择菜单">
          <el-checkbox v-model="toggle">展开/关闭</el-checkbox>
          <el-checkbox v-model="isAllSelected">全选/反选</el-checkbox>
          <el-tree
            ref="tree"
            :data="menus"
            show-checkbox
            :props="props"
            node-key="id"
            @check="treeChange"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="handleDialog">取 消</el-button>
        <el-button type="primary" size="small" @click="save">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { findRolesByPage, findAllPermissions, saveRolePermissions, findRolePermissions, updateRolePermissions, removeRole } from '@/api/auth/roles'
import mix from '@/mixins'
export default {
  mixins: [mix],
  data() {
    return {
      toggle: false,
      isAllSelected: false,
      state: 1,
      isShowDialog: false,
      // 是否显示加载中
      loading: false,
      menuIds: [],
      formData: {
        'id': '',
        'permissionIds': [],
        'remark': '',
        'roleCode': '',
        'roleName': ''
      },
      list: [],
      menus: [],
      props: {
        label: 'title'
      }
    }
  },
  watch: {
    isAllSelected(val) {
      console.log(val)
      if (val) {
        // 全选
        this.$refs.tree.setCheckedKeys(this.menuIds)
        this.formData.permissionIds = this.menuIds
      } else {
        // 反选
        this.$refs.tree.setCheckedKeys([])
        this.formData.permissionIds = []
      }
    },
    toggle(val) {
      for (var i in this.$refs.tree.store.nodesMap) {
        this.$refs.tree.store.nodesMap[i].expanded = val
      }
    }
  },

  created() {
    this.init()
  },

  mounted() {

  },

  methods: {
    // 编辑角色弹框
    goEdit(id, state) {
      this.state = state
      this.isShowDialog = true
      findAllPermissions()
        .then(res => {
          this.menus = res.data.menus
          this.getIds(res.data.menus, this.menuIds)
          console.log(this.menuIds)
        })
      findRolePermissions(id)
        .then(res => {
          console.log(res)
          this.formData = res.data.role
          if (this.formData.permissionIds) {
            this.$refs.tree.setCheckedKeys(this.formData.permissionIds)
          }
          if (this.menuIds.length === this.formData.permissionIds.length) {
            this.isAllSelected = true
          }
        })
    },
    // 保存角色信息
    save() {
      console.log(this.formData)
      if (this.state) {
        // 新增
        saveRolePermissions(this.formData)
          .then(res => {
            console.log(res)
            this.isShowDialog = false
            this.init()
          })
      } else {
        // 修改
        updateRolePermissions(this.formData)
          .then(res => {
            console.log(res)
            this.isShowDialog = false
            this.init()
          })
      }
    },

    treeChange(val, val1) {
      console.log(val1)
      if (val1.checkedKeys.length === this.menuIds.length) {
        this.isAllSelected = true
      } else {
        this.isAllSelected = false
      }
      this.formData.permissionIds = val1.checkedKeys
    },
    // 新增角色弹框
    goAddRoles(state) {
      this.state = state
      this.isShowDialog = true
      findAllPermissions()
        .then(res => {
          this.menus = res.data.menus
          this.getIds(res.data.menus, this.menuIds)
        })
    },
    // 删除角色
    del(id) {
      this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 删除角色
        removeRole(id)
          .then(res => {
            console.log(res)
            if (res.success) {
              this.init()
            } else {
              this.$message.error(res.message)
            }
          })
      }).catch(() => {
        this.$message.info('你已取消删除操作')
      })
    },

    handleDialog() {
      this.isShowDialog = false
      this.formData = this.$options.data().formData
      this.$refs.tree.setCheckedKeys([])
      this.isAllSelected = false
      this.toggle = false
      this.menuIds = []
    },

    // 获取列表
    init() {
      this.loading = true
      findRolesByPage(this.paginationParams.start, this.paginationParams.limit)
        .then(res => {
          console.log(res)
          this.list = res.data.rows
          this.paginationParams.total = res.data.total
          this.loading = false
        })
    },
    // 每页多少条改变时触发（main.js中切换页码中文）
    handleSizeChange(e) {
      this.paginationParams.limit = e
      this.init()
    },
    // 当前页码发生改变触发
    handleCurrentChange(e) {
      this.paginationParams.start = e
      this.init()
    },
    getIds(arr, result) {
      arr.forEach(ele => {
        result.push(ele.id)
        if (ele.children && ele.children.length) {
          this.getIds(ele.children, result)
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>

</style>
